/*******************************************************************************
 * Copyright (c) 2009-2011 ETCORE Labs. All rights reserved. 
 * 
 * This software is the confidential and proprietary information of ETCORE Labs.
 * You shall not disclose such confidential information and shall use it
 * only in accordance with the terms of the license agreement you entered into
 * with ETCORE Labs. 
 * 
 * Support can be obtained from support forums at:  http://www.etcore.com/
 * /
 *******************************************************************************/
package etcore.webapp.grouptalk.user.action;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import etcore.webapp.grouptalk.common.action.AbstractAction;
import etcore.webapp.grouptalk.common.config.Config;
import etcore.webapp.grouptalk.common.config.MessageNamespaces;
import etcore.webapp.grouptalk.common.config.Messages;
import etcore.webapp.grouptalk.common.config.PageConstants;
import etcore.webapp.grouptalk.common.object.Comment;
import etcore.webapp.grouptalk.common.object.Group;
import etcore.webapp.grouptalk.common.object.Message;
import etcore.webapp.grouptalk.common.object.ReplyTemplate;
import etcore.webapp.grouptalk.common.service.CommentService;
import etcore.webapp.grouptalk.common.service.GroupService;
import etcore.webapp.grouptalk.common.service.MessageService;
import etcore.webapp.grouptalk.common.service.ReplyTemplateService;
import etcore.webapp.grouptalk.user.object.Favourite;
import etcore.webapp.grouptalk.user.object.Focus;
import etcore.webapp.grouptalk.user.object.Member;
import etcore.webapp.grouptalk.user.object.User;
import etcore.webapp.grouptalk.user.service.FavouriteService;
import etcore.webapp.grouptalk.user.service.FocusService;
import etcore.webapp.grouptalk.user.service.MemberService;
import etcore.webapp.grouptalk.user.service.UserService;
import etcore.webapp.grouptalk.util.DateUtil;
import etcore.webapp.grouptalk.util.MD5;
import etcore.webapp.grouptalk.util.Symbols;

/**
 * This action validates the request and set the corresponding attributes
 * required by the userShow page
 * 
 * @author ETCORE GroupTalk Developers
 * 
 */
public class UserShowAction extends AbstractAction {

	private static final long serialVersionUID = -8914408350934547114L;
	// validate result
	public static final int ACCESS_ALLOWED = 0;
	public static final int ERROR = 1;
	public static final int NOT_LOGGED = 2;

	// utility constants

	public static final String UID = "uid";
	public static final String DEL = "del";
	public static final String ONE = "1";
	public static final String MINUS_ONE = "-1";
	public static final String ON = "on";
	public static final String TO_USER = "toUser";
	public static final String TO_ADMIN = "toAdmin";
	public static final String SORT = "sort";
	public static final String ADMIN = "admin";
	public static final String ADD_USER = "addUser";
	public static final String FOLLOW_USERS = "followUsers";
	public static final String FOLLOW_GROUPS = "followGroups";
	public static final String ADD_FAVOURITE = "addFavourite";
	public static final String ADD_COMMENT = "addComment";
	public static final String REG_TIME = "regTime";
	public static final String ADD_USERNAME = "addUserName";
	public static final String LAST_TIME = "lastTime";
	public static final String LOG_NUM = "loginNum";
	public static final String DAYS = "days";

	public static final String MIN_REPLIES = "minReplies";
	public static final String MAX_REPLIES = "maxReplies";

	public static final String DAY_AMOUNT = "dayAmount";
	public static final String PWD = "pwd";
	public static final String IS_LOCK = "isLock";

	public static final String INPUT_DATE = "inputDate";
	public static final String COUNT = "count";
	public static final String REDUCE = "reduceAllocation";
	public static final String ADD = "addAllocation";

	@Override
	public int validate(HttpServletRequest request, HttpServletResponse response) {

		boolean isAdmin = (Boolean) request.getAttribute(PageConstants.ISADMIN);
		boolean notLogged = (Boolean) request
				.getAttribute(PageConstants.NOTLOGGED);
		if (notLogged)
			return NOT_LOGGED;
		if (isAdmin) {

			return ACCESS_ALLOWED;
		}

		return ERROR;

	}

	@Override
	public String getForward(HttpServletRequest request, int validationResult) {
		if (NOT_LOGGED == validationResult) {
			request.setAttribute("init", "login");
			return "/";
		}
		if (ERROR == validationResult)
			return PageConstants.ACTION_PATH_ERROR;
		return PageConstants.PAGE_PATH_USERSHOW;
	}

	@Override
	public String getRedirect(HttpServletRequest request, int validationResult) {
		// TODO Auto-generated method stub

		return null;
	}

	@Override
	public void execute(int validationResult, HttpServletRequest request,
			HttpServletResponse response) {
		// TODO Auto-generated method stub
		if (ACCESS_ALLOWED == validationResult) {

			deleteUser(request);
			autoFollowUsers(request);
			autoFollowGroups(request);
			autoAddFavourite(request);
			autoAddComment(request);
			toAdmin(request);
			toUser(request);
			lockUser(request);
			unlockUser(request);
			addUser(request);
			getUsers(request);

		}

	}

	private void deleteUser(HttpServletRequest request) {
		String del = request.getParameter(DEL);
		String userId = request.getParameter(UID);
		if (del != null && del.equals(ONE) && userId != null) {
			UserService userService = new UserService();
			MemberService memberService = new MemberService();
			User delUser = userService.findById(new Integer(userId));
			if (delUser != null && !delUser.getUserName().equals(User.ROOT)
					&& !memberService.isSysAdmin(delUser.getUserName()))
				userService.deleteSingle(delUser);
			returnSuccess(request);
		}
	}

	private void lockUser(HttpServletRequest request) {
		String lock = request.getParameter("lock");
		String userId = request.getParameter(UID);

		if (lock != null && lock.equals(ONE) && userId != null) {
			UserService userService = new UserService();
			MemberService memberService = new MemberService();
			User lockUser = userService.findById(new Integer(userId));
			if (lockUser != null && !lockUser.getUserName().equals(User.ROOT)
					&& !memberService.isSysAdmin(lockUser.getUserName())) {
				if (lock.equals(ONE))
					lockUser.setIsLock(1);

				userService.merge(lockUser);

				returnSuccess(request);

			}

		}
	}

	private void addUser(HttpServletRequest request) {
		String cmd = request.getParameter(PageConstants.CMD);

		if (ADD_USER.equals(cmd)) {
			UserService userService = new UserService();
			String userName = request.getParameter(ADD_USERNAME);
			String pwd = request.getParameter(PWD);
			String isLockStr = request.getParameter(IS_LOCK);
			String isAdmin = request.getParameter(ADMIN);
			HttpSession session = request.getSession(true);
			String lang = (String) session.getAttribute(Messages.LANG);
			String msg = null;

			List<User> registered = userService.findByProperty(
					PageConstants.USERNAME, userName);
			if (registered != null && registered.size() > 0) {
				if (lang != null && lang.equals(Messages.LANG_EN)) {
					msg = Messages.getELabel(Messages.MSG_USER_NAME_SAME);
				} else {
					msg = Messages.getLabel(Messages.MSG_USER_NAME_SAME);
				}
				request.setAttribute(PageConstants.MSG, msg);
				return;
			}

			User newUser = new User();

			MD5 md5 = new MD5();
			newUser.setPwd(md5.getMD5ofStr(pwd));

			newUser.setUserName(userName);

			newUser.setLastIp(request.getRemoteAddr());
			newUser.setRegTime(DateUtil.getTime(Config.getProperty(Config.HOURS_DIFFERENCE)));
			int isLock = Integer.parseInt(isLockStr);
			newUser.setIsLock(isLock);

			userService.save(newUser);

			if (Messages.TRUE.equals(isAdmin)) {
				MemberService memberService = new MemberService();
				GroupService groupService = new GroupService();

				Group rootGroup = groupService.findByName(Group.ROOTS);
				if (rootGroup == null)
					return;
				Member member = memberService.findByUsernameAndGid(userName,
						rootGroup.getId());
				if (member == null) {
					member = new Member();
					member.setGid(rootGroup.getId());
					member.setUserName(userName);
					member.setMytype(Member.MEMBER);
					member.setApp(new Integer(1));

					member.setLocked(new Integer(0));

					member.setMainnum(new Integer(0));
					member.setCreateTime(DateUtil.getTime(Config.getProperty(Config.HOURS_DIFFERENCE)));
					member.setTotalnum(new Integer(0));
					member.setLastTime(DateUtil.getTime(Config.getProperty(Config.HOURS_DIFFERENCE)));
					member.setEnergy(new Integer(0));
					memberService.save(member);

				} else if (member != null
						&& !(Member.OWNER.equals(member.getMytype()))) {
					member.setMytype(Member.MEMBER);
					memberService.merge(member);
				}

			}
			returnSuccess(request);
		}

	}

	private void unlockUser(HttpServletRequest request) {
		String unlock = request.getParameter("unlock");
		String userId = request.getParameter(UID);

		if (unlock != null && (unlock.equals(MINUS_ONE) || unlock.equals(ONE))
				&& userId != null) {
			UserService userService = new UserService();
			// MemberService memberService = new MemberService();
			User lockUser = userService.findById(new Integer(userId));
			if (lockUser != null && !lockUser.getUserName().equals(User.ROOT)) {
				lockUser.setIsLock(0);

				userService.merge(lockUser);

				returnSuccess(request);

			}

		}
	}

	private void toAdmin(HttpServletRequest request) {
		MemberService memberService = new MemberService();

		String name = request.getParameter(PageConstants.NAME);

		String toAdmin = request.getParameter(TO_ADMIN);
		Member member = null;

		if (name != null && ON.equals(toAdmin)) {

			try {
				name = new String(name.getBytes("iso-8859-1"), ("utf-8"));
			} catch (Exception e) {
				e.printStackTrace();
			}
			GroupService groupService = new GroupService();

			Group rootGroup = groupService.findByName(Group.ROOTS);
			if (rootGroup == null)
				return;
			member = memberService
					.findByUsernameAndGid(name, rootGroup.getId());
			if (member == null) {
				member = new Member();
				member.setGid(rootGroup.getId());
				member.setUserName(name);
				member.setMytype(Member.MEMBER);
				member.setApp(new Integer(1));

				member.setLocked(new Integer(0));

				member.setMainnum(new Integer(0));
				member.setCreateTime(DateUtil.getTime(Config.getProperty(Config.HOURS_DIFFERENCE)));
				member.setTotalnum(new Integer(0));
				member.setLastTime(DateUtil.getTime(Config.getProperty(Config.HOURS_DIFFERENCE)));
				member.setEnergy(new Integer(0));
				memberService.save(member);

			} else if (member != null
					&& !(Member.OWNER.equals(member.getMytype()))) {
				member.setMytype(Member.MEMBER);
				memberService.merge(member);
			}
			returnSuccess(request);
		}
	}

	private void toUser(HttpServletRequest request) {
		MemberService memberService = new MemberService();

		String name = request.getParameter(PageConstants.NAME);
		String toUser = request.getParameter(TO_USER);
		Member member = null;
		HttpSession session = request.getSession(true);
		User session_user = (User) session
				.getAttribute(PageConstants.SESSIONUSER);
		if (name != null)
			try {
				name = new String(name.getBytes("iso-8859-1"), ("utf-8"));
			} catch (Exception e) {
				e.printStackTrace();
			}
		if (name != null && ON.equals(toUser) && session_user != null
				&& !name.equals(session_user.getUserName())) {
			GroupService groupService = new GroupService();

			Group rootGroup = groupService.findByName(Group.ROOTS);
			if (rootGroup == null)
				return;
			member = memberService
					.findByUsernameAndGid(name, rootGroup.getId());
			if (member != null && !(Member.OWNER.equals(member.getMytype()))) {
				// gm.setMytype("member");
				memberService.deleteSingle(member);
				returnSuccess(request);

			}

		}

	}

	private void returnSuccess(HttpServletRequest request) {
		String msg = null;
		HttpSession session = request.getSession(true);
		String lang = (String) session.getAttribute(Messages.LANG);
		if (lang != null && lang.equals(Messages.LANG_EN)) {
			msg = Messages.getELabel(Messages.MSG_SUCCESS);
		} else {
			msg = Messages.getLabel(Messages.MSG_SUCCESS);
		}
		request.setAttribute(PageConstants.MSG, msg);
	}

	private void autoFollowUsers(HttpServletRequest request) {
		MemberService memberService = new MemberService();
		FocusService focusService = new FocusService();
		UserService userService = new UserService();
		HttpSession session = request.getSession(true);
		long sysAdminCount = memberService.getSysAdminNum();
		long totalFollowing = sysAdminCount * (sysAdminCount - 1);
		request.setAttribute("maxFollowingSize", totalFollowing);
		long followed = focusService.findAllFollowedSizeBetweenAdmins();

		String cmd = request.getParameter(PageConstants.CMD);
		if (FOLLOW_USERS.equals(cmd)) {
			String days = request.getParameter(DAYS);
			String dayAmount = request.getParameter(DAY_AMOUNT);
			if (days == null || Symbols.BLANK.equals(days))
				return;
			if (dayAmount == null || Symbols.BLANK.equals(dayAmount))
				return;
			int daysValue = Integer.parseInt(days);
			int dayAmountValue = Integer.parseInt(dayAmount);
			long dayFollowed = 0, notFollowedSize = 0;
			if (daysValue * dayAmountValue > (totalFollowing - followed)) {
				String msg = null;
				String lang = (String) session.getAttribute(Messages.LANG);
				if (lang != null && lang.equals(Messages.LANG_EN)) {
					msg = Messages.getELabel(Messages.MSG_ALLOCATION_LACKNESS);
				} else {
					msg = Messages.getLabel(Messages.MSG_ALLOCATION_LACKNESS);
				}
				request.setAttribute(PageConstants.MSG, msg);

				return;
			}
			String fromUser = null, toUser = null;
			int MAX_SECONDS = 10 * 60 * 60, MIN_START_SECONDS = 8 * 60 * 60, seconds = 0;
			String addTime = null;
			for (int i = 0; i <= daysValue; i++) {
				String targetDate = DateUtil.getNextDate(i);
				dayFollowed = focusService
						.findAllFollowedSizeBetweenAdmins(targetDate);

				for (int j = 0; j < dayAmountValue - dayFollowed; j++) {
					long maxFromUsers = focusService
							.findAdminsSizeByMaxHisFollowed(sysAdminCount - 1);
					int random = (int) (Math.random() * maxFromUsers);
					List<Object[]> fromUsers = focusService
							.findAdminsByMaxHisFollowed(
									(int) (sysAdminCount - 1), random, 1);
					if (fromUsers == null || fromUsers.size() == 0)
						continue;
					fromUser = (String) fromUsers.get(0)[0];
					notFollowedSize = focusService
							.findSizeOfNotFollowedAdmin(fromUser);
					int random2 = (int) (Math.random() * notFollowedSize);
					List<String> toUsers = focusService.findNotFollowedAdmins(
							fromUser, random2, 1);
					if (toUsers == null || toUsers.size() == 0)
						continue;

					toUser = toUsers.get(0);

					if (fromUser.equals(toUser)
							|| focusService.isAdded(fromUser, toUser))
						continue;
					Focus focus = new Focus();
					seconds = (int) (Math.random() * MAX_SECONDS)
							+ MIN_START_SECONDS;
					addTime = DateUtil.getLaterTime(targetDate, seconds);
					focus.setAddTime(addTime);
					focus.setFromUser(fromUser);
					focus.setToUser(toUser);
					focusService.save(focus);
					User user = userService.findByUserName(fromUser);
					if (user != null) {
						user.setLastTime(DateUtil.getTime(Config.getProperty(Config.HOURS_DIFFERENCE)));
						user.setLoginNum(user.getLoginNum() + 2);
						userService.merge(user);
					}
				}
			}

		}
		followed = focusService.findAllFollowedSizeBetweenAdmins();
		request.setAttribute("existingFollowingSize", followed);
	}

	private void autoFollowGroups(HttpServletRequest request) {
		MemberService memberService = new MemberService();
		GroupService groupService = new GroupService();
		UserService userService = new UserService();
		long sysAdminCount = memberService.getSysAdminNum();
		long communityGroupSize = groupService.findSizeByProperty(
				PageConstants.OPEN, 2);
		long totalFollowing = sysAdminCount * communityGroupSize;
		request.setAttribute("maxFollowingGroups", totalFollowing);
		long followed = memberService.findSizeOfAdminFollowing(2);
		HttpSession session = request.getSession(true);
		String cmd = request.getParameter(PageConstants.CMD);
		if (FOLLOW_GROUPS.equals(cmd)) {
			String days = request.getParameter(DAYS);
			String dayAmount = request.getParameter(DAY_AMOUNT);
			if (days == null || Symbols.BLANK.equals(days))
				return;
			if (dayAmount == null || Symbols.BLANK.equals(dayAmount))
				return;
			int daysValue = Integer.parseInt(days);
			int dayAmountValue = Integer.parseInt(dayAmount);
			long dayFollowed = 0, notFollowedSize = 0;
			if (daysValue * dayAmountValue > (totalFollowing - followed)) {
				String msg = null;
				String lang = (String) session.getAttribute(Messages.LANG);
				if (lang != null && lang.equals(Messages.LANG_EN)) {
					msg = Messages.getELabel(Messages.MSG_ALLOCATION_LACKNESS);
				} else {
					msg = Messages.getLabel(Messages.MSG_ALLOCATION_LACKNESS);
				}
				request.setAttribute(PageConstants.MSG, msg);

				return;
			}
			String fromUser = null;
			Integer targetGid = null;
			int MAX_SECONDS = 10 * 60 * 60, MIN_START_SECONDS = 8 * 60 * 60, seconds = 0;
			String addTime = null;
			for (int i = 0; i <= daysValue; i++) {
				String targetDate = DateUtil.getNextDate(i);
				dayFollowed = memberService.findSizeOfAdminFollowing(2,
						targetDate);

				for (int j = 0; j < dayAmountValue - dayFollowed; j++) {
					long maxFromUsers = memberService
							.findAdminsSizeByMaxHisFollowed(2,
									communityGroupSize);
					int random = (int) (Math.random() * maxFromUsers);
					List<Object[]> fromUsers = memberService
							.findAdminsByMaxHisFollowed(2, communityGroupSize,
									random, 1);
					if (fromUsers == null || fromUsers.size() == 0)
						continue;
					fromUser = (String) fromUsers.get(0)[0];
					notFollowedSize = memberService
							.findSizeOfAdminNotFollowing(2, fromUser);
					int random2 = (int) (Math.random() * notFollowedSize);
					List<Integer> groups = memberService
							.findGroupsOfAdminNotFollowing(2, fromUser,
									random2, 1);
					if (groups == null || groups.size() == 0)
						continue;

					targetGid = groups.get(0);

					if (memberService.isIn(fromUser, targetGid) > 0)
						continue;
					Member member = new Member();
					seconds = (int) (Math.random() * MAX_SECONDS)
							+ MIN_START_SECONDS;
					addTime = DateUtil.getLaterTime(targetDate, seconds);
					member.setCreateTime(addTime);
					member.setGid(targetGid);

					member.setUserName(fromUser);
					memberService.save(member);
					User user = userService.findByUserName(fromUser);
					if (user != null) {
						user.setLastTime(DateUtil.getTime(Config.getProperty(Config.HOURS_DIFFERENCE)));
						user.setLoginNum(user.getLoginNum() + 2);
						userService.merge(user);
					}
				}
			}

		}
		followed = memberService.findSizeOfAdminFollowing(2);
		request.setAttribute("existingFollowingGroups", followed);
	}

	private void autoAddFavourite(HttpServletRequest request) {
		FavouriteService favouriteService = new FavouriteService();
		MessageService messageService = new MessageService();
		MemberService memberService = new MemberService();
		UserService userService = new UserService();
		long sysAdminCount = memberService.getSysAdminNum();
		long maxSize = messageService.findSizeOfPublicMessages(
				PageConstants.UP, 1);
		long added = favouriteService.findSizeOfAdminFavourites(
				PageConstants.UP, 1);
		String cmd = request.getParameter(PageConstants.CMD);
		if (ADD_FAVOURITE.equals(cmd)) {
			HttpSession session = request.getSession(true);
			String days = request.getParameter(DAYS);
			String dayAmount = request.getParameter(DAY_AMOUNT);
			if (days == null || Symbols.BLANK.equals(days))
				return;
			if (dayAmount == null || Symbols.BLANK.equals(dayAmount))
				return;
			int daysValue = Integer.parseInt(days);
			int dayAmountValue = Integer.parseInt(dayAmount);
			long dayAdded = 0;
			if (daysValue * dayAmountValue > (maxSize - added)) {
				String msg = null;
				String lang = (String) session.getAttribute(Messages.LANG);
				if (lang != null && lang.equals(Messages.LANG_EN)) {
					msg = Messages.getELabel(Messages.MSG_ALLOCATION_LACKNESS);
				} else {
					msg = Messages.getLabel(Messages.MSG_ALLOCATION_LACKNESS);
				}
				request.setAttribute(PageConstants.MSG, msg);

				return;
			}
			String fromUser = null;
			Integer targetMid = null;
			int MAX_SECONDS = 10 * 60 * 60, MIN_START_SECONDS = 8 * 60 * 60, seconds = 0;
			String addTime = null;
			for (int i = 0; i <= daysValue; i++) {
				String targetDate = DateUtil.getNextDate(i);
				dayAdded = favouriteService.findSizeOfAdminFavourites(
						targetDate, PageConstants.UP, 1);

				for (int j = 0; j < dayAmountValue - dayAdded; j++) {

					int random = (int) (Math.random() * sysAdminCount);
					fromUser = memberService.getSystemAdmins(random, 1);

					maxSize = messageService.findSizeOfPublicMessages(
							PageConstants.UP, 1);
					int random2 = (int) (Math.random() * maxSize);
					@SuppressWarnings("unchecked")
					List<Object[]> messages = messageService
							.findPublicMessages(PageConstants.UP, 1, random2, 1);

					targetMid = (Integer) messages.get(0)[0];

					if (favouriteService.isAdded(fromUser, targetMid))
						continue;
					Favourite favourite = new Favourite();
					seconds = (int) (Math.random() * MAX_SECONDS)
							+ MIN_START_SECONDS;
					addTime = DateUtil.getLaterTime(targetDate, seconds);
					favourite.setAddTime(addTime);
					favourite.setMid(targetMid);
					favourite.setUserName(fromUser);
					favouriteService.save(favourite);
					User user = userService.findByUserName(fromUser);
					if (user != null) {
						user.setLastTime(DateUtil.getTime(Config.getProperty(Config.HOURS_DIFFERENCE)));
						user.setLoginNum(user.getLoginNum() + 3);
						userService.merge(user);
					}
				}
			}

		}
		added = favouriteService.findSizeOfAdminFavourites(PageConstants.UP, 1);
		request.setAttribute("existingAddedFavourite", added);
		request.setAttribute("maxFavourite", maxSize);
	}

	@SuppressWarnings("rawtypes")
	private void autoAddComment(HttpServletRequest request) {
		CommentService commentService = new CommentService();
		MessageService messageService = new MessageService();
		MemberService memberService = new MemberService();
		UserService userService = new UserService();
		ReplyTemplateService replyTemplateSevice = new ReplyTemplateService();
		int MAX_SECONDS_LATER = 24 * 60 * 60;
		long sysAdminCount = memberService.getSysAdminNum();
		int MAX = 300;
		long commonRepliesCount = replyTemplateSevice.findSizeByProperty(
				PageConstants.TID, 0);
		long repliesCount = replyTemplateSevice.findSize();
		request.setAttribute("publicRepliesCount", commonRepliesCount);
		request.setAttribute("repliesCount", repliesCount);

		String cmd = request.getParameter(PageConstants.CMD);
		if (ADD_COMMENT.equals(cmd)) {
			HttpSession session = request.getSession(true);
			String startDate = request.getParameter(PageConstants.START_DATE);
			String endDate = request.getParameter(PageConstants.END_DATE);
			String minReplies = request.getParameter(MIN_REPLIES);
			String maxReplies = request.getParameter(MAX_REPLIES);
			int dateError = 0;
			if (startDate == null || Symbols.BLANK.equals(startDate.trim())) {
				dateError = 1;
			}
			if (dateError == 0
					&& (endDate == null || Symbols.BLANK.equals(endDate.trim())))
				endDate = startDate;

			int gap = 0;
			if (dateError == 0)
				gap = DateUtil.getQuot(endDate, startDate);

			if (dateError == 1 || gap < 0) {
				String msg = null;
				String lang = (String) session.getAttribute(Messages.LANG);
				if (lang != null && lang.equals(Messages.LANG_EN)) {
					msg = Messages.getELabel(Messages.MSG_DATE_ERROR);
				} else {
					msg = Messages.getLabel(Messages.MSG_DATE_ERROR);
				}
				request.setAttribute(PageConstants.MSG, msg);

				return;

			}
			int min = 0, max = 0;

			if (minReplies == null || Symbols.BLANK.equals(minReplies))

				min = 0;
			else
				min = Integer.parseInt(minReplies);
			if (maxReplies == null || Symbols.BLANK.equals(maxReplies))

				max = 0;
			else
				max = Integer.parseInt(maxReplies);
			if (min == 0 && max == 0 || min > max)
				return;

			String fromUser = null, lastTime = null;
			long targetMsgSize = messageService
					.findSizeOfPublicMessagesByInterval(startDate, endDate);

			if (targetMsgSize > MAX)
				targetMsgSize = MAX;

			List messages = messageService.findPublicMessagesByInterval(
					startDate, endDate, 0, (int) targetMsgSize);
			int tempSize = 0,dateGap=0;
			for (int i = 0; i < messages.size(); i++) {
				Object[] message = (Object[]) messages.get(i);
				long templateCount = replyTemplateSevice
						.findSizeByCommonAndTid((Integer) message[1]);
				if (templateCount == 0)
					return;
				int randomSize = (int) (Math.random() * (max - min)) + min;
				tempSize = (int) commentService.findSizeByProperty(
						PageConstants.GMID, message[0]);
				randomSize -= tempSize;
				
				for (int j = 0; j < randomSize; j++) {
					int randomUesrIndex = (int) (Math.random() * sysAdminCount);
					fromUser = memberService
							.getSystemAdmins(randomUesrIndex, 1);
					int randomTemplateIndex = (int) (Math.random() * templateCount);

					ReplyTemplate replyTemplate = replyTemplateSevice
							.findByCommonAndTid((Integer) message[1],
									randomTemplateIndex, 1).get(0);
					dateGap=DateUtil.getQuot(DateUtil.getDate(), (String)message[3])+1;
					int seconds = (int) (Math.random() * MAX_SECONDS_LATER*dateGap);
					lastTime = DateUtil.getLaterTime((String) message[3],
							seconds);
					Comment comment = new Comment();

					comment.setGmid((Integer) message[0]);
					comment.setUserName(fromUser);
					comment.setTime(lastTime);
					comment.setContent(replyTemplate.getContent());
					commentService.save(comment);

					User user = userService.findByUserName(fromUser);
					if (user != null) {
						user.setLastTime(lastTime);
						user.setLoginNum(user.getLoginNum() + 1);
						userService.merge(user);

					}
				}
				Message m = messageService.findById((Integer) message[0]);
				m.setNum(m.getNum() + randomSize);
				messageService.merge(m);

			}

		}

	}

	private void allocate(HttpServletRequest request) {
		String cmd = request.getParameter(PageConstants.CMD);

		if (!(ADD.equals(cmd) || REDUCE.equals(cmd)))
			return;
		HttpSession session = request.getSession(true);
		String startDate = request.getParameter(PageConstants.START_DATE);
		String endDate = request.getParameter(PageConstants.END_DATE);
		String countStr = request.getParameter(COUNT);
		if (countStr == null || Symbols.BLANK.equals(countStr))
			return;
		int dateError = 0;
		if (startDate == null || Symbols.BLANK.equals(startDate.trim())) {
			dateError = 1;
		}
		if (dateError == 0
				&& (endDate == null || Symbols.BLANK.equals(endDate.trim())))
			endDate = startDate;

		int gap = 0;
		if (dateError == 0)
			gap = DateUtil.getQuot(endDate, startDate);

		if (dateError == 1 || gap < 0) {
			String msg = null;
			String lang = (String) session.getAttribute(Messages.LANG);
			if (lang != null && lang.equals(Messages.LANG_EN)) {
				msg = Messages.getELabel(Messages.MSG_DATE_ERROR);
			} else {
				msg = Messages.getLabel(Messages.MSG_DATE_ERROR);
			}
			request.setAttribute(PageConstants.MSG, msg);

			return;

		}
		UserService userService = new UserService();

		int count = Integer.parseInt(countStr);
		if (ADD.equals(cmd)) {

			long hidden = userService.findSizeByProperty(IS_LOCK, -1);
			if (count * gap > hidden) {
				String msg = null;
				String lang = (String) session.getAttribute(Messages.LANG);
				if (lang != null && lang.equals(Messages.LANG_EN)) {
					msg = Messages.getELabel(Messages.MSG_ALLOCATION_LACKNESS);
				} else {
					msg = Messages.getLabel(Messages.MSG_ALLOCATION_LACKNESS);
				}
				request.setAttribute(PageConstants.MSG, msg);

				return;
			}

			for (int i = 0; i <= gap; i++) {
				String targetDate = DateUtil.getNextDate(startDate, i);
				List<User> users = userService.findByProperty(IS_LOCK, -1, 0,
						count);
				for (User user : users) {
					user.setRegTime(targetDate);

					user.setIsLock(0);
					userService.merge(user);
				}

			}

		} else if (REDUCE.equals(cmd)) {

			long check = DateUtil.getQuot(startDate, DateUtil.getDate());
			if (check <= 0) {
				String msg = null;
				String lang = (String) session.getAttribute(Messages.LANG);
				if (lang != null && lang.equals(Messages.LANG_EN)) {
					msg = Messages.getELabel(Messages.REDUCE_OLD_ERROR);
				} else {
					msg = Messages.getLabel(Messages.REDUCE_OLD_ERROR);
				}
				request.setAttribute(PageConstants.MSG, msg);

				return;
			}
			for (int i = 0; i <= gap; i++) {
				String targetDate = DateUtil.getNextDate(startDate, i);
				List<User> users = userService.findByFutureDays(targetDate, 0,
						0, count);
				for (User user : users) {

					user.setIsLock(-1);

					userService.merge(user);
				}

			}
		}

	}

	private void getUsers(HttpServletRequest request) {
		allocate(request);
		MemberService memberService = new MemberService();
		int intpageid = 1;
		String sort = request.getParameter(SORT);
		int unit = 25;
		String unitStr = request.getParameter(PageConstants.UNIT);
		if (unitStr != null)
			unit = Integer.parseInt(unitStr);
		long all = 0;
		int begin, pagenums;
		String pageid = request.getParameter(PageConstants.PAGEID);
		if (pageid != null)
			intpageid = Integer.parseInt(pageid);
		String userNameStr = request.getParameter(PageConstants.USERNAME);
		UserService userService = new UserService();
		String cmd = request.getParameter(PageConstants.CMD);
		if (userNameStr != null && cmd == null)

			all = userService.searchSizeByProperty(PageConstants.USERNAME,
					userNameStr);
		else if (ADMIN.equals(sort))
			all = memberService.getAllSysAdminNum();
		else
			all = userService.findSize();
		pagenums = (int) ((all + unit - 1) / unit);
		begin = unit * (intpageid - 1);
		long hidden = userService.findSizeByProperty(IS_LOCK, -1);
		long todayAdded = userService.findSizeByFutureDays(0);
		request.setAttribute("hidden", hidden);
		request.setAttribute("todayAdded", todayAdded);
		List<User> userList = null;
		if (userNameStr != null)
			userList = userService.searchByProperty(PageConstants.USERNAME,
					userNameStr, begin, unit);
		else if (ADMIN.equals(sort)) {
			userList = new ArrayList<User>();
			String users = memberService.getAllSystemAdmins(begin, unit);
			String[] adminArray = users.split(Symbols.COMMA);
			for (String admin : adminArray) {
				userList.add(userService.findByUserName(admin));
			}

		} else if (sort != null
				&& (sort.equals(LOG_NUM) || sort.equals(LAST_TIME) || sort
						.equals(REG_TIME)))
			userList = userService.findAllBySort(begin, unit, sort);
		else
			userList = userService.findAll(begin, unit);
		for (User user : userList) {
			if (memberService.isSysAdmin(user.getUserName()))
				request.setAttribute(user.getId() + PageConstants.ISADMIN, true);
			else
				request.setAttribute(user.getId() + PageConstants.ISADMIN,
						false);
		}

		request.setAttribute(PageConstants.PAGENUMS, pagenums);
		request.setAttribute(PageConstants.ALL, all);
		request.setAttribute(PageConstants.UNIT, unit);
		request.setAttribute(PageConstants.INTPAGEID, intpageid);
		request.setAttribute(PageConstants.USERS, userList);
		getUserAnalysis(request);
	}

	private void getUserAnalysis(HttpServletRequest request) {
		int analysisUnit = 4;

		String inputDate = request.getParameter(INPUT_DATE);

		UserService userService = new UserService();

		if (inputDate == null || Symbols.BLANK.equals(inputDate.trim())) {
			for (int i = 1; i <= analysisUnit; i++) {
				long previous = userService.findSizeByFutureDays(i);
				request.setAttribute("date" + i, DateUtil.getPreviousDate(i));
				request.setAttribute("added" + i, previous);
			}
			String currentDate = DateUtil.getDate();
			request.setAttribute("currentDate", currentDate);
			request.setAttribute("currentAdded",
					userService.findSizeByFutureDays(currentDate, 0));
			for (int i = -1; i >= -analysisUnit; i--) {
				long future = userService.findSizeByFutureDays(i);
				request.setAttribute("added" + i, future);
				request.setAttribute("date" + i, DateUtil.getNextDate(-i));
			}
		} else {
			for (int i = 1; i <= analysisUnit; i++) {
				long previous = userService.findSizeByFutureDays(inputDate, i);
				request.setAttribute("date" + i,
						DateUtil.getPreviousDate(inputDate, i));
				request.setAttribute("added" + i, previous);
			}
			request.setAttribute("currentDate", inputDate);
			request.setAttribute("currentAdded",
					userService.findSizeByFutureDays(inputDate, 0));
			for (int i = -1; i >= -analysisUnit; i--) {
				long future = userService.findSizeByFutureDays(inputDate, i);
				request.setAttribute("added" + i, future);
				request.setAttribute("date" + i,
						DateUtil.getNextDate(inputDate, -i));
			}
		}
		request.setAttribute("analysisUnit", analysisUnit);
	}

	@Override
	public boolean isForward(int validationResult) {
		// TODO Auto-generated method stub
		return true;
	}

	@Override
	public boolean enablePostLoad() {
		// TODO Auto-generated method stub
		return false;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see etcore.webapp.grouptalk.controller.action.AbstractAction#
	 * buildSelfContextAndAttributes(int, javax.servlet.http.HttpServletRequest)
	 */
	@Override
	public List<String> getNamespacesOfMessages(HttpServletRequest request) {
		// TODO Auto-generated method stub
		List<String> namespaces = new ArrayList<String>();
		namespaces.add(MessageNamespaces.GROUP_ADMIN);
		return namespaces;
	}

}
